#!/bin/bash
#
# USAGE:
#	s_readfiles
#
# DESCRIPTION:
#  s_readfiles is a builtin ADORE process.  
#  It runs the DORIS step with the same name. 
#
# It is the same as step M_READFILES but then for the slave image. See M_READFILES (? m_readfiles) for more information on this step.
#
# In order to be compatible with official DORIS release v4.02, the current ADORE implementation makes calls for reading Gamma SLC files, if $slcType is specified as gamma. This will be removed when DORIS v4.03 is released, because it will support reading Gamma SLC files within DORIS.
#
# INPUT:
#
# OUTPUT:
#  Outputs generated by Doris:
#   Slave result file
#
# REFERENCE:
# http://doris.tudelft.nl/usermanual/node37.html

slcType=`echo ${slcType-undefined} | tr "[:upper:]" "[:lower:]"`
#echo ${slcType}
#check if slcType exists
case "${slcType}" in
  gamma)
    echo "Reading Gamma SLC"
    slaveDataFolder=`dirname "${s_in_dat}"`
    #get parFile SysFile
    parFile=`ls ${dataFolder}/${slave}/${gammaParFile} 2>/dev/null | tr -d '\n'`
    if [ ! -e "${parFile}" ]; then
      echo " I can not find the parameter file ("${gammaParFile}") inside ${slaveDataFolder}"
      return -1;
    fi

    sysFile=`ls ${dataFolder}/${slave}/${gammaSysFile} 2>/dev/null | tr -d '\n'`
    if [ ! -e "${sysFile}" ]; then
      echo " I can not find the parameter file ("${gammaSysFile}") inside ${slaveDataFolder}"
      return -1;
    fi

    gammaReadfiles.csh ${parFile} ${sysFile} ${s_in_dat} ${gammaByteSwap} > ${outputFolder}/${slave}.res
    [ $? -eq 0 ] && echo "${dorisProcess}: SUCCESS"
    unset slaveDataFolder parFile sysFile    
  ;;
    adore)
    echo "Reading ADORE SLC"
    if [ -e "${s_in_lea}" ];then
      #copy header
      headerLine=`grep -n Start_process_control ${s_in_lea} | cut -d":" -f1`
      headerLine=$(( ${headerLine} - 1 ))
      head -n ${headerLine} ${s_in_lea} > ${s_resfile}
      tailLine=`grep -n End_process_control ${s_in_lea} | cut -d":" -f1`
      grep -A $(( $tailLine - $headerLine )) Start_process_control ${s_in_lea} | tr "1" "0" >> ${s_resfile}
      # copy readfiles 
      copyRes.sh ${s_in_lea} readfiles ${s_resfile}
      modifyRes.sh ${s_resfile} readfiles "Datafile" ${s_in_dat}
    else
      error "ADORE SLC files also require a leader file set."
      return -1;
    fi
  ;;
  gmtsar)
    echo "Reading GMTSAR SLC"
    if [ -e "${s_in_lea}" ] && [ -e "${s_in_dat}" ] && [ -e "${s_in_vol}" ]; then
      #run the m_readfiles script
      gmtsarReadfiles.py ${s_in_dat} ${s_in_lea} ${s_in_vol} > ${s_resfile}
      [ $? -eq 0 ] && echo "${dorisProcess}: SUCCESS"
    else
      error "GMTSAR SLC files require the *.PRM, *.SLC and *.LEA files in m_in_lea, m_in_dat and m_in_vol."
      return -1;
    fi
  ;;
  *)
    #if [ "${slcType-undefined}" == "undefined" ]; then
    #standard processing
    pp ${dorisProcess}
    doris ${outputFolder}/${dorisProcess}.drs
    [ $? -eq 0 ] && echo "${dorisProcess}: SUCCESS"
  ;;
esac
